/**
 * 音频处理管理器
 * 专门处理音频相关的GAIA命令，避免与设备信息模块冲突
 */

// 音频处理相关的GAIA命令常量
const AudioCommand = {
  // EQ相关命令
  V1_GET_EQ_STATE: 0x00,                    // 获取EQ状态
  V1_GET_EQ_SET: 0x02,                      // 获取当前预设
  V1_SET_EQ_SET: 0x03,                      // 设置预设
  V1_GET_USER_SET_CONFIGURATION: 0x05,      // 获取用户EQ配置
  V1_SET_USER_SET_CONFIGURATION: 0x06,      // 设置用户EQ配置
  
  // 音频处理相关
  V1_GET_AVAILABLE_EQ_PRE_SETS: 0x01,       // 获取可用预设列表
  V1_GET_EQ_PARAMETER: 0x07,                // 获取EQ参数
  V1_SET_EQ_PARAMETER: 0x08,                // 设置EQ参数
}

// GAIA协议常量
const AudioVendorID = {
  QTIL_V3: 0x001D,      // Qualcomm Technologies International, Ltd. (Version 3)
}

const AudioFeatureID = {
  MUSIC_PROCESSING: 0x05,  // 音乐处理功能
}

class AudioManager {
  constructor() {
    this.isConnected = false
    this.gaiaManager = null
    this.onCommandResponse = null
    this.bleDataCallback = null
    
    // 音频处理相关状态
    this.eqBands = []
    this.currentPreset = 0
    this.eqEnabled = false
    
    // 默认EQ频段配置
    this.defaultEQBands = [
      { frequency: 60, gain: 0, q: 1.0, filterType: 'PEAKING', id: 0 },
      { frequency: 170, gain: 0, q: 1.0, filterType: 'PEAKING', id: 1 },
      { frequency: 310, gain: 0, q: 1.0, filterType: 'PEAKING', id: 2 },
      { frequency: 600, gain: 0, q: 1.0, filterType: 'PEAKING', id: 3 },
      { frequency: 1000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 4 },
      { frequency: 3000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 5 },
      { frequency: 6000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 6 },
      { frequency: 12000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 7 },
      { frequency: 14000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 8 },
      { frequency: 16000, gain: 0, q: 1.0, filterType: 'PEAKING', id: 9 }
    ]
  }

  // 初始化音频管理器
  init(gaiaManager) {
    this.gaiaManager = gaiaManager
    this.isConnected = gaiaManager ? gaiaManager.isConnected : false
    
    console.log('🎵 [音频管理器] 初始化完成')
  }

  // 设置连接状态
  setConnected(connected) {
    this.isConnected = connected
    console.log('🎵 [音频管理器] 连接状态:', connected)
  }

  // 设置命令响应回调
  setOnCommandResponse(callback) {
    this.onCommandResponse = callback
    console.log('🎵 [音频管理器] 设置命令响应回调')
  }

  // 设置BLE数据回调
  setBleDataCallback(callback) {
    this.bleDataCallback = callback
    console.log('🎵 [音频管理器] 设置BLE数据回调')
  }

  // 构建音频处理GAIA命令
  buildAudioCommand(commandId, payload = new Uint8Array(0)) {
    try {
      if (!this.gaiaManager) {
        throw new Error('GaiaManager未初始化')
      }

      // 使用GaiaManager的构建方法，但指定音频处理的参数
      const vendorId = AudioVendorID.QTIL_V3
      const featureId = AudioFeatureID.MUSIC_PROCESSING
      const type = 0x00 // 请求类型
      
      // 构建COMMAND_VALUE (16位)
      const commandValue = (featureId << 9) | (type << 7) | commandId
      
      // 构建完整的GAIA PDU
      const command = new Uint8Array(4 + payload.length)
      command[0] = (vendorId >> 8) & 0xFF
      command[1] = vendorId & 0xFF
      command[2] = (commandValue >> 8) & 0xFF
      command[3] = commandValue & 0xFF
      
      // 添加payload
      for (let i = 0; i < payload.length; i++) {
        command[4 + i] = payload[i]
      }
      
      console.log(`🎵 [音频管理器] 构建命令: 0x${commandId.toString(16).padStart(2, '0')}`, command)
      return command.buffer
      
    } catch (error) {
      console.error('🎵 [音频管理器] 构建命令失败:', error)
      throw error
    }
  }

  // 发送音频处理命令
  async sendAudioCommand(commandId, payload = new Uint8Array(0)) {
    try {
      if (!this.isConnected) {
        throw new Error('设备未连接')
      }

      if (!this.gaiaManager) {
        throw new Error('GaiaManager未初始化')
      }

      console.log(`🎵 [音频管理器] 发送命令: 0x${commandId.toString(16).padStart(2, '0')}`)
      
      // 使用GaiaManager的sendCommandWithVendorAndFeature方法
      await this.gaiaManager.sendCommandWithVendorAndFeature(
        commandId,
        payload,
        AudioVendorID.QTIL_V3,
        AudioFeatureID.MUSIC_PROCESSING
      )
      
      return true
      
    } catch (error) {
      console.error('🎵 [音频管理器] 发送命令失败:', error)
      throw error
    }
  }

  // 等待音频处理命令响应
  async waitForAudioResponse(commandId, timeout = 5000) {
    try {
      if (!this.gaiaManager) {
        throw new Error('GaiaManager未初始化')
      }

      console.log(`🎵 [音频管理器] 等待响应: 0x${commandId.toString(16).padStart(2, '0')}`)
      
      // 使用GaiaManager的等待响应方法
      const response = await this.gaiaManager.waitForResponse(commandId, timeout)
      
      return response
      
    } catch (error) {
      console.error('🎵 [音频管理器] 等待响应失败:', error)
      throw error
    }
  }

  // 获取用户EQ配置
  async getUserSetConfiguration() {
    try {
      if (!this.isConnected) {
        return { success: false, error: '设备未连接' }
      }

      console.log('🎵 [音频管理器] 开始从设备获取用户EQ配置')

      // 发送V1_GET_USER_SET_CONFIGURATION命令
      const payload = new Uint8Array(2)
      payload[0] = 0x00 // bandStart = 0
      payload[1] = 0x09 // bandEnd = 9 (假设有10个频段：0-9)
      
      await this.sendAudioCommand(AudioCommand.V1_GET_USER_SET_CONFIGURATION, payload)

      // 等待响应
      const response = await this.waitForAudioResponse(AudioCommand.V1_GET_USER_SET_CONFIGURATION, 5000)
      console.log('🎵 [音频管理器] 用户EQ配置响应:', response)

      if (response.success && response.data && response.data.length > 0) {
        // 解析设备返回的EQ数据
        const userBands = this.parseUserSetConfiguration(response.data)
        console.log('🎵 [音频管理器] 解析后的用户EQ配置:', userBands)
        
        return { success: true, data: userBands }
      }
      
    } catch (error) {
      console.error('🎵 [音频管理器] 获取用户EQ配置失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 解析用户设置配置数据
  parseUserSetConfiguration(data) {
    try {
      console.log('🎵 [音频管理器] 解析用户EQ配置数据:', data)
      
      if (!data || data.length === 0) {
        console.warn('🎵 [音频管理器] EQ配置数据为空')
        return this.getDefaultEQBands()
      }

      const userBands = []
      let offset = 0

      // 解析每个频段的数据
      while (offset < data.length) {
        if (offset + 7 > data.length) {
          console.warn('🎵 [音频管理器] 数据长度不足，停止解析')
          break
        }

        // 解析频段信息 (7字节)
        const frequency = (data[offset] | (data[offset + 1] << 8)) // 频率 (2字节)
        const q = (data[offset + 2] | (data[offset + 3] << 8)) / 1000.0 // Q值 (2字节，除以1000)
        const filterType = data[offset + 4] // 滤波器类型 (1字节)
        const gain = (data[offset + 5] | (data[offset + 6] << 8)) // 增益 (2字节，有符号)

        // 转换增益 (从设备单位转换为dB，参考Android GAIN_FACTOR = 60.0)
        const gainDb = gain / 60.0

        // 转换滤波器类型
        const filterTypeStr = this.getFilterType(filterType)

        userBands.push({
          frequency: frequency,
          gain: gainDb,
          q: q,
          filterType: filterTypeStr,
          id: userBands.length
        })

        offset += 7
      }

      console.log('🎵 [音频管理器] 解析完成，共', userBands.length, '个频段')
      return userBands

    } catch (error) {
      console.error('🎵 [音频管理器] 解析用户EQ配置失败:', error)
      return this.getDefaultEQBands()
    }
  }

  // 获取滤波器类型字符串
  getFilterType(filterType) {
    const filterTypes = {
      0: 'PEAKING',
      1: 'LOW_SHELF',
      2: 'HIGH_SHELF',
      3: 'LOW_PASS',
      4: 'HIGH_PASS',
      5: 'BAND_PASS',
      6: 'NOTCH'
    }
    return filterTypes[filterType] || 'PEAKING'
  }

  // 获取默认EQ频段配置
  getDefaultEQBands() {
    return [...this.defaultEQBands]
  }

  // 解析音频处理GAIA响应
  parseAudioResponse(hexData) {
    try {
      console.log('🎵 [音频管理器] 解析音频响应:', hexData)
      
      // 检查数据长度
      if (!hexData || hexData.length < 8) {
        console.log('🎵 [音频管理器] 数据长度不足，跳过解析')
        return null
      }
      
      // 按照GAIA协议格式解析
      const vendorIdHex = hexData.substring(0, 4)
      const commandValueHex = hexData.substring(4, 8)
      const payloadHex = hexData.substring(8)
      
      const vendorId = parseInt(vendorIdHex, 16)
      const commandValue = parseInt(commandValueHex, 16)
      
      // 解析COMMAND_VALUE
      const featureId = (commandValue >> 9) & 0x7F
      const type = (commandValue >> 7) & 0x03
      const commandId = commandValue & 0x7F
      
      // 检查是否是音频处理命令
      if (vendorId !== AudioVendorID.QTIL_V3 || featureId !== AudioFeatureID.MUSIC_PROCESSING) {
        console.log('🎵 [音频管理器] 非音频处理命令，跳过')
        return null
      }
      
      // 将payload从hex转换为字节数组
      const payload = this.hexToBytes(payloadHex)
      
      console.log(`🎵 [音频管理器] 音频命令: 0x${commandId.toString(16).padStart(2, '0')}`, payload)
      
      // 回调处理
      if (this.onCommandResponse && typeof this.onCommandResponse === 'function') {
        this.onCommandResponse(commandId, payload, 'response', vendorId)
      }
      
      return {
        commandId,
        payload,
        type: 'response',
        vendorId
      }
      
    } catch (error) {
      console.error('🎵 [音频管理器] 解析音频响应失败:', error)
      return null
    }
  }

  // 处理BLE原始数据
  handleBleData(data) {
    try {
      console.log('🎵 [音频管理器] 处理BLE原始数据:', data)
      
      // 解析hexData
      const hexData = data.value
      const commandId = data.id
      const timestamp = data.timestamp
      
      console.log(`🎵 [音频管理器] hexData: ${hexData}, commandId: ${commandId}, timestamp: ${timestamp}`)
      
      // 尝试解析音频响应
      const audioResponse = this.parseAudioResponse(hexData)
      
      if (audioResponse) {
        console.log('🎵 [音频管理器] 成功解析音频响应')
        return audioResponse
      } else {
        console.log('🎵 [音频管理器] 非音频响应，忽略')
        return null
      }
      
    } catch (error) {
      console.error('🎵 [音频管理器] 处理BLE数据失败:', error)
      return null
    }
  }

  // 十六进制字符串转字节数组
  hexToBytes(hex) {
    if (!hex || hex.length === 0) {
      return new Uint8Array(0)
    }
    
    const bytes = []
    for (let i = 0; i < hex.length; i += 2) {
      bytes.push(parseInt(hex.substr(i, 2), 16))
    }
    return new Uint8Array(bytes)
  }

  // 设置EQ频段增益
  async setEQBandGain(bandIndex, gain) {
    try {
      if (!this.isConnected) {
        throw new Error('设备未连接')
      }

      console.log(`🎵 [音频管理器] 设置频段${bandIndex}增益: ${gain}dB`)

      // 构建设置命令的payload
      const payload = new Uint8Array(3)
      payload[0] = bandIndex // 频段索引
      payload[1] = (gain * 100) & 0xFF // 增益低字节
      payload[2] = ((gain * 100) >> 8) & 0xFF // 增益高字节

      await this.sendAudioCommand(AudioCommand.V1_SET_USER_SET_CONFIGURATION, payload)

      // 等待响应
      const response = await this.waitForAudioResponse(AudioCommand.V1_SET_USER_SET_CONFIGURATION, 3000)

      if (response.success) {
        console.log('🎵 [音频管理器] EQ频段增益设置成功')
        return { success: true }
      } else {
        console.warn('🎵 [音频管理器] EQ频段增益设置失败')
        return { success: false, error: '设置失败' }
      }

    } catch (error) {
      console.error('🎵 [音频管理器] 设置EQ频段增益失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取当前EQ预设
  async getCurrentPreset() {
    try {
      if (!this.isConnected) {
        return { success: false, error: '设备未连接' }
      }

      console.log('🎵 [音频管理器] 获取当前EQ预设')

      await this.sendAudioCommand(AudioCommand.V1_GET_EQ_SET)

      // 等待响应
      const response = await this.waitForAudioResponse(AudioCommand.V1_GET_EQ_SET, 3000)

      if (response.success && response.data && response.data.length > 0) {
        const preset = response.data[0]
        console.log('🎵 [音频管理器] 当前预设:', preset)
        return { success: true, data: preset }
      } else {
        console.warn('🎵 [音频管理器] 获取预设失败')
        return { success: false, error: '获取失败' }
      }

    } catch (error) {
      console.error('🎵 [音频管理器] 获取当前预设失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 设置EQ预设
  async setPreset(presetIndex) {
    try {
      if (!this.isConnected) {
        throw new Error('设备未连接')
      }

      console.log(`🎵 [音频管理器] 设置EQ预设: ${presetIndex}`)

      const payload = new Uint8Array(1)
      payload[0] = presetIndex

      await this.sendAudioCommand(AudioCommand.V1_SET_EQ_SET, payload)

      // 等待响应
      const response = await this.waitForAudioResponse(AudioCommand.V1_SET_EQ_SET, 3000)

      if (response.success) {
        console.log('🎵 [音频管理器] EQ预设设置成功')
        this.currentPreset = presetIndex
        return { success: true }
      } else {
        console.warn('🎵 [音频管理器] EQ预设设置失败')
        return { success: false, error: '设置失败' }
      }

    } catch (error) {
      console.error('🎵 [音频管理器] 设置EQ预设失败:', error)
      return { success: false, error: error.message }
    }
  }
}

// 创建全局实例
const audioManager = new AudioManager()

module.exports = audioManager
